package com.spring.starter.redis.web;

import org.redisson.Redisson;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @auther zhangwj
 * @date 2020/7/13 9:04 上午
 */
@RestController
public class RedisController {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    private final static String KEY = "myKey";

    @RequestMapping(value = "put")
    public String putValue(@RequestParam(value = "value") Integer value) {
        stringRedisTemplate.opsForValue().set(KEY, value.toString());
        return "ok";
    }

    Lock lock = new ReentrantLock();

    @Resource
    private Redisson redisson;

    @RequestMapping(value = "get")
    public void getValue() {
        lock.lock();
        int value = Integer.parseInt(stringRedisTemplate.opsForValue().get(KEY));
        System.out.println("value=" + value);
        if (value > 0) {
            value--;
            stringRedisTemplate.opsForValue().set(KEY, String.valueOf(value));
        } else {
            System.out.println("无库存");
        }
        lock.unlock();
    }
}
